//
//  MHAuditListViewModel.m
//  MiaoCircle
//
//  Created by 许正荣 on 2018/5/10.
//  Copyright © 2018年 acgera. All rights reserved.
//

#import "MHAuditListViewModel.h"
#import "MHCircleMember.h"
#import "MHAuditItemViewModel.h"
#import "MHAuditInfoViewModel.h"

@implementation MHAuditListViewModel
- (instancetype)initWithServices:(id<MHViewModelServices>)services params:(NSDictionary *)params{
    if (self = [super initWithServices:services params:params]) {
        self.info = params[MHViewModelUtilKey];
    }
    return self;
}


-(void)initialize
{
    [super initialize];
    self.title = @"审批请求";
    self.shouldPullUpToLoadMore = YES;
    self.shouldPullDownToRefresh = YES;
    /// 没有数据时，隐藏底部刷新控件
    self.shouldEndRefreshingWithNoMoreData = NO;
    
    @weakify(self);
    RAC(self, auditList) = self.requestRemoteDataCommand.executionSignals.switchToLatest;
    /// 数据源
    RAC(self,dataSource) = [RACObserve(self, auditList) map:^(NSArray * audits) {
        @strongify(self)
     return [self dataSourceWithcircleMembers:audits];
    }];
        
    self.auditCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(MHCircleMember  *member ) {
        MHAuditInfoViewModel *infoModel = [[MHAuditInfoViewModel alloc] initWithServices:self.services params:@{MHViewModelUtilKey:member}];
        [self.services pushViewModel:infoModel animated:YES];
        return [RACSignal empty];
    }];
    
}

- (RACSignal *)requestRemoteDataSignalWithPage:(NSUInteger)page{
    
    NSArray * (^mapcircleMembers)(NSArray *) = ^(NSArray *audits) {
        if (page == 1) {
            /// 下拉刷新
        } else {
            /// 上拉加载
            audits = @[(self.auditList ?: @[]).rac_sequence, audits.rac_sequence].rac_sequence.flatten.array;
        }
        return audits;
    };
    return [[[self.services.client getAuditMemberListWithCircleId:self.info.autoId pageNum:page pageSize:self.perPage] mh_parsedResults] map:mapcircleMembers];
}



#pragma mark - 辅助方法
- (NSArray *)dataSourceWithcircleMembers:(NSArray *)blackList {
    if (MHObjectIsNil(blackList) || blackList.count == 0) return nil;
    NSMutableArray *viewModels = [[blackList.rac_sequence map:^(MHCircleMember *circleMember) {
        MHAuditItemViewModel *viewModel  = [[MHAuditItemViewModel alloc] initWithModel:circleMember];
        viewModel.auditCommond = self.auditCommand;
        return viewModel;
    }].array mutableCopy];
    return viewModels ?: @[] ;
}
@end
